/**   
 * @Title: ResourceService.java 
 * @Package com.betterjr.modules.workflow.snaker.core 
 * @Description: 流程实例操作类
 * @author licz
 * @date 2017年10月30日 下午3:03:48  
 */
package com.betterjr.modules.risk.loanmanage.service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.betterjr.common.selectkey.SerialGenerator;
import com.betterjr.common.service.BaseService;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.BetterDateUtils;
import com.betterjr.common.utils.UserUtils;
import com.betterjr.mapper.pagehelper.Page;
import com.betterjr.modules.risk.loan.service.LoanProjectRelationService;
import com.betterjr.modules.risk.loanmanage.dao.LoanDataMapper;
import com.betterjr.modules.risk.loanmanage.dubbo.LoanManageDubboService;
import com.betterjr.modules.risk.loanmanage.entity.LoanData;
import com.betterjr.modules.risk.loanmanage.entity.PaymentData;
import com.betterjr.modules.risk.loanmanage.entity.PaymentPlan;
import com.betterjr.modules.risk.loanmanage.util.BetterBeanUtils;

/** 
 * @ClassName: LoanDataService 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author licz
 * @date 2018年7月13日 下午3:43:07 
 *  
 */
@Service
public class LoanDataService extends BaseService<LoanDataMapper, LoanData> {
    //// -1没完成(默认)，0完成，1部分完成，2逾期
    @Inject
    PaymentPlanService paymentPlanService;

    @Inject
    private LoanProjectRelationService loanProjectRelationService;

    @Inject
    LoanManageDubboService loanManageDubboService;

    @Inject
    PaymentDataService paymentDataService;

    @Inject
    RepaymentDetailsService repaymentDetailsService;

    public Page<LoanData> listLoanDataByPage(final LoanData loanData, final int pageNum, final int pageSize) {
        final Long count = this.mapper.queryLoanDatasCount(loanData);
        List<LoanData> resultList = new ArrayList<>();
        if (count > 0) {
            resultList = this.mapper.queryLoanDatasByPage(loanData, (pageNum - 1) * pageSize, pageSize);
        }

        return Page.listToPage(resultList, pageNum, pageSize, (int) Math.ceil(count.doubleValue() / pageSize),
                (pageNum - 1) * pageSize, count);
    }

    public Page<LoanData> listLoanDataByPage(final Map<String, Object> param, final int pageNum, final int pageSize) {

        final LoanData loanData = new LoanData();
        BetterBeanUtils.copyProperties2Bean(loanData, param);
        BTAssert.notNull(loanData, "参数不允许为空！");
        return listLoanDataByPage(loanData, pageNum, pageSize);
    }

    /** 
     * @Title: manuallyCompletedRePayment 
     * @Description: 手动完成放款
     * @param id 
     * @throws 
     * @author licz
     * @date 2018年6月29日 上午10:40:01 
     */
    public void manuallyCompletedRePayment(final Long id) {
        // 1.取消云资金管理的计划
        paymentPlanService.cancelPaymentPlanByLoanDataId(id);
        // 2.修改放款表状态 完成 ，
        final LoanData loanData = new LoanData();
        loanData.setId(id);
        loanData.setStatus("0");
        this.updateByPrimaryKeySelective(loanData);
        // 3. 修改还款明细表 状态处于没完成的为 “ 手动完成状态”
        repaymentDetailsService.manuallyCompletedByLoanDataId(id);
        // TODO 回写 贷款项目状态 ，数据中心交易数据状态
        loanManageDubboService.callDataCenterChangeLoanStatus(id, "2");// 1表示未结清，2表示已结清

        loanProjectRelationService.saveLoanFinish(this.selectByPrimaryKey(id).getContractId());

    }

    public LoanData saveLoanData(final Map<String, Object> param) {

        final LoanData loanData = new LoanData();
        BetterBeanUtils.copyProperties2Bean(loanData, param);
        BTAssert.notNull(loanData, "参数不允许为空！");

        loanData.setCreatorId(UserUtils.getUser().getId());
        loanData.setCreator(UserUtils.getUser().getName());
        loanData.setCreateDate(Timestamp.valueOf(BetterDateUtils.getDateTime()));
        loanData.setUpdateCreatorId(UserUtils.getUser().getId());
        loanData.setUpdateCreator(UserUtils.getUser().getName());
        loanData.setUpdateDate(Timestamp.valueOf(BetterDateUtils.getDateTime()));
        if (!ObjectUtils.isEmpty(loanData.getId())) {
            this.updateByPrimaryKeySelective(loanData);
        } else {
            final Long baseId = SerialGenerator.getLongValue(LoanData.selectKey);
            loanData.setId(baseId);
            this.insertSelective(loanData);
        }
        return loanData;
    }

    /** 
     * @Title: homeReportCountData 
     * @Description: 首页报表统计数据  4块 ,  根据查询条件统计数据，主表放款数据表
     * @param param   ，资金方首页 fundProviderId  不能为空  ，运维平台，不传参数统计所有 ,所有参数需要与数据库类型一直
     * @return 
     * @throws 
     * @author licz
     * @date 2018年7月13日 下午3:43:08 
     */
    public List<Map<String, String>> homeReportCountData(final Map<String, Object> param) {
        /* BTAssert.notNull(param, "参数不允许为空！");
        final String fundProviderId = (String) param.get("fundProviderId");
        BTAssert.isTrue(StringUtils.isNotBlank(fundProviderId), "fundProviderId参数不允许为空！");
        final List<LoanData> loanDataList = this.selectByProperty("fundProviderId", fundProviderId);*/
        final String fundProviderId = (String) param.get("fundProviderId");
        List<LoanData> loanDataList = null;

        if (StringUtils.isNotBlank(fundProviderId)) {
            loanDataList = this.selectByProperty("fundProviderId", fundProviderId);
        } else {
            loanDataList = this.selectAll();
        }

        final List<Long> loanDataIdList = new ArrayList<>();
        final List<Long> overduePalnIdList = new ArrayList<>();// 逾期的计划id
        final List<PaymentPlan> overduePaymentPlanList = new ArrayList<>();// 逾期的计划id 对应计划数据
        final List<PaymentData> overduePaymentDataList = new ArrayList<>();// 逾期计划id关联的扣款数据
        // 已放款
        BigDecimal alreadyLoanAmount = new BigDecimal(0);
        int alreadyLoanNum = 0;
        final Map<String, String> alreadyLoanMap = new HashMap<>();
        for (final LoanData loanData : loanDataList) {
            alreadyLoanAmount = alreadyLoanAmount.add(loanData.getLoanAmount());
            alreadyLoanNum = alreadyLoanNum + 1;
            loanDataIdList.add(loanData.getId());
        }
        alreadyLoanMap.put("已放款总额", alreadyLoanAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        alreadyLoanMap.put("已放款总笔数", alreadyLoanNum + "");

        // 查询扣款计划表 获取统计数据
        final List<PaymentPlan> paymentPlanList = paymentPlanService.selectByListProperty("loanDataId", loanDataIdList);

        // 应该收款
        BigDecimal shouldReceiptAmount = new BigDecimal(0);
        int shouldReceiptNum = 0;
        final Map<String, String> shouldReceiptMap = new HashMap<>();
        for (final PaymentPlan paymentPlan : paymentPlanList) {
            shouldReceiptAmount = shouldReceiptAmount.add(paymentPlan.getAmount());
            shouldReceiptNum = shouldReceiptNum + 1;

            if (!"0".equals(paymentPlan.getStatus())
                    && paymentPlan.getPaymentDate().before(Timestamp.valueOf(BetterDateUtils.getDateTime()))) {
                overduePalnIdList.add(paymentPlan.getId());
            }

        }

        shouldReceiptMap.put("应收款总额", shouldReceiptAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        shouldReceiptMap.put("应收款总笔数", shouldReceiptNum + "");

        // 查询 扣款数据表 获取统计数据
        final List<PaymentData> paymentDataList = paymentDataService.selectByListProperty("loanDataId", loanDataIdList);

        // 已收款
        BigDecimal alreadyReceiptAmount = new BigDecimal(0);
        int alreadyReceiptNum = 0;
        final Map<String, String> alreadyReceiptMap = new HashMap<>();
        for (final PaymentData paymentData : paymentDataList) {
            alreadyReceiptAmount = alreadyReceiptAmount.add(paymentData.getRealAmount());
            alreadyReceiptNum = alreadyReceiptNum + 1;
            if (overduePalnIdList.contains(paymentData.getPaymentPlanId())) {
                overduePaymentDataList.add(paymentData);
            }
        }

        alreadyReceiptMap.put("已收款总额", alreadyReceiptAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        alreadyReceiptMap.put("已收款总笔数", alreadyReceiptNum + "");

        // 已逾期
        BigDecimal alreadyOverdueAmount = new BigDecimal(0);
        int alreadyOverdueNum = 0;
        final Map<String, String> alreadyOverdueMap = new HashMap<>();
        for (final PaymentPlan paymentPlan : overduePaymentPlanList) {
            BigDecimal realAmount = new BigDecimal(0);
            for (final PaymentData paymentData : overduePaymentDataList) {
                if (paymentPlan.getId() == paymentData.getPaymentPlanId()) {
                    realAmount = realAmount.add(paymentData.getRealAmount());
                }
            }
            alreadyOverdueAmount = alreadyOverdueAmount.add(paymentPlan.getAmount().subtract(realAmount));
            alreadyOverdueNum = alreadyOverdueNum + 1;
        }
        alreadyOverdueMap.put("已逾期总额", alreadyOverdueAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        alreadyOverdueMap.put("已逾期总笔数", alreadyOverdueNum + "");

        final List<Map<String, String>> result = new ArrayList<>();
        result.add(alreadyLoanMap);
        result.add(shouldReceiptMap);
        result.add(alreadyReceiptMap);
        result.add(alreadyOverdueMap);
        return result;
    }

}
